package com.kust.smarthome.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kust.smarthome.web.model.LinkPerson;
import com.kust.smarthome.web.model.User;
import com.kust.smarthome.web.service.ILinkPersonService;
import com.kust.smarthome.web.service.IUserService;
import com.kust.smarthome.web.vo.LinkPersonVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@RestController
@RequestMapping("/linkPerson")
@Api(value = "链接关系人设别相关", tags = {"user-tag"})
@Slf4j
public class LinkPersonController {

    @Resource
    private ILinkPersonService linkPersonService;

    @Resource
    private IUserService userService;

    @PostMapping("/addApp")
    public String addApp(HttpServletRequest request, @Validated LinkPersonVo linkPersonVo, BindingResult result, Principal principal) {
        String jwt = request.getHeader("Authorization");

        if (result.hasErrors()) {
            String msg = result.getFieldError().getDefaultMessage();
            log.error(msg);
            return msg;
        }

        User user = userService.getByUsername(principal.getName());
        LinkPerson linkPerson = new LinkPerson()
                .setUuidCode(linkPersonVo.getUuidCode())
                .setToken(jwt)
                .setUserId(user.getId())
                .setPersonId(linkPersonVo.getPersonId());

        return linkPersonService.save(linkPerson) ? "成功!" : "失败!";

    }

    @GetMapping("/getPerson")
    public LinkPerson getPerson(String uuidCode) {

        if (uuidCode == null)
            return null;

        QueryWrapper<LinkPerson> query = new QueryWrapper<>();
        query.eq("uuid_code", uuidCode);
        LinkPerson linkPerson = linkPersonService.getOne(query);

        if (linkPerson == null)
            return null;

        linkPersonService.removeById(linkPerson.getId());
        return linkPerson;
    }
}
